class VoicePlayer {
  lastTask = null
  audio = document.createElement('AUDIO')
  play(url, success, ended, error) {
    var loaded = false
    if (this.lastTask) {
      this.destroyLastTask()
    }
    this.lastTask = {
      loaded: false,
      success: success,
      ended: ended,
      error: error,
      timeUpdate: () => {
        if (!this.lastTask.loaded && this.audio.currentTime > 0) {
          this.lastTask.success && this.lastTask.success()
        }
      }
    }
    this.audio.src = url
    this.audio.autoplay = false
    this.audio.addEventListener('timeupdate', this.lastTask.timeUpdate, false)
    // this.audio.addEventListener('play', this.lastTask.success, false)
    this.audio.addEventListener('ended', this.lastTask.ended, false)
    this.audio.addEventListener('error', this.lastTask.error, false)
    this.audio.play()
  }
  destroyLastTask() {
    this.audio.pause()
    this.audio.removeEventListener('timeupdate', this.lastTask.timeUpdate, false)
    // this.audio.removeEventListener('play', this.lastTask.success, false)
    this.audio.removeEventListener('ended', this.lastTask.ended, false)
    this.audio.removeEventListener('error', this.lastTask.error, false)
  }
  stop() {
    if (this.lastTask) {
      this.destroyLastTask()
    }
  }
}
module.exports = new VoicePlayer()
